package com.maxatime.controller;
//import com.lrm.util.MD5Utils;
import com.maxatime.utils.MD5Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailSendException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
 * @Auther: 梁玉杰
 * @Date: 2021/8/19 16:16
 * @Description: TODO
 */
@Controller
public class ErController {
//
//
//        @Autowired
//        private UserService userService;

        private final Logger logger = LoggerFactory.getLogger(this.getClass());

        @Value("${mail.fromMail.sender}")
        private String sender;// 发送者

        @Autowired
        private JavaMailSender javaMailSender;

        public Map<String, Object> resultMap = new HashMap<>();

        @RequestMapping("/sendEmail")
        //转换json数据  @ResponseBody
        //random
        @ResponseBody
        public String sendEmail(String email) {
            SimpleMailMessage message = new SimpleMailMessage();
            String code = VerifyCode(6);    //随机数生成6位验证码
            message.setFrom(sender);
            message.setTo(email);
            message.setSubject("智慧校园");// 标题
            message.setText("【智慧校园】你的验证码为："+code+"，有效时间为5分钟(若不是本人操作，可忽略该条邮件)");// 内容
            try {
                javaMailSender.send(message);
                logger.info("文本邮件发送成功！");
                saveCode(code);
                return "success";
            }catch (MailSendException e){
                logger.error("目标邮箱不存在");
                return "false";
            } catch (Exception e) {
                logger.error("文本邮件发送异常！", e);
                return "failure";
            }
        }

        private String VerifyCode(int n){
            Random r = new Random();
            StringBuffer sb =new StringBuffer();
            for(int i = 0;i < n;i ++){
                int ran1 = r.nextInt(10);
                sb.append(String.valueOf(ran1));
            }
//        System.out.println(sb);
            return sb.toString();
        }

        //保存验证码和时间
        private void saveCode(String code){
            SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
            Calendar c = Calendar.getInstance();
            c.add(Calendar.MINUTE, 5);
            String currentTime = sf.format(c.getTime());// 生成5分钟后时间，用户校验是否过期

            String hash =  MD5Utils.code(code);//生成MD5值
            resultMap.put("hash", hash);
            resultMap.put("tamp", currentTime);
        }

    /**
     * @Author 梁玉杰
     * @Description //TODO
     * @Date 2021/8/19 19:43
     * @Param
     * @return
     * 思路：判断此时时间与上次存的验证码的生成时间之差是否大于五分钟，
     *      若大于，则提示超时；若没有大于，再将用户输入的验证码进行加密，
     *      接着判断用户输入的验证码与最先保存的验证码是否一致
     *      （这里也可以通过验证码的解密，然后将解密后的验证码和用户输入的直接比对）
     *      jpa show.sql 打印sql语句
     **/
    @PostMapping("/register")
    public String login(@RequestParam String username, @RequestParam String password, @RequestParam String email,
                        @RequestParam String identify,RedirectAttributes attributes) {
        if (resultMap.size() ==0){
            return "tourist/register";
        }
        //判断验证码是否正确
        String requestHash = resultMap.get("hash").toString();

        String tamp = resultMap.get("tamp").toString();
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");//当前时间
        Calendar c = Calendar.getInstance();
        String currentTime = sf.format(c.getTime());
        if (tamp.compareTo(currentTime) > 0) {
            String hash =  MD5Utils.code(identify);//生成MD5值
            if (hash.equalsIgnoreCase(requestHash)){
                //校验成功
                attributes.addFlashAttribute("m", "恭喜！现在，你可以登录你的用户名。");
                return "redirect:/tourist";
            }else {
                //验证码不正确，校验失败
                System.out.println("2");
                attributes.addFlashAttribute("message", "验证码输入不正确");
                return "redirect:/tourist/register";
            }
        } else {
            // 超时
            System.out.println("3");
            attributes.addFlashAttribute("message", "验证码已过期");
            return "redirect:/tourist/register";
        }

    }


}
